﻿using System;
using System.Threading.Tasks;
using KCPExampleProtocal;
using PENet;

namespace KCPExampleClient
{
    public class ClientStart
    {
        public static KCPNet<ClientSession, NetMsg> client;
        static Task<bool> checkTask = null;
        public static void Main(string[] args)
        {
            client = new KCPNet<ClientSession, NetMsg>();
            client.StartAsClient("127.0.0.1",17666);
            checkTask = client.ConnectServer(200,5000);
            Task.Run(ConnectCheck);
            while (true)
            {
                string ipt = Console.ReadLine();
                if (ipt == "quit")
                {
                    client.CloseClient();
                    break;
                }
                else
                {
                    client.clientSession.SendMsg(new NetMsg()
                    {
                        info = ipt
                    });
                }
            }

            Console.ReadKey();
        }
        private static int counter = 0;
        static async void ConnectCheck()
        {
            while (true)
            {
                await Task.Delay(3000);
                if (checkTask != null && checkTask.IsCompleted)
                {
                    if (checkTask.Result)
                    {
                        KCPTool.ColorLog(KCPLogColor.Green, "ConnectServer Success.");
                        checkTask = null;
                        // 自动重连
                        await Task.Run(SendPingMsg);
                    }
                    else
                    {
                        ++counter;
                        if(counter > 4) {
                            KCPTool.Error(string.Format("Connect Failed {0} Times,Check Your Network Connection.", counter));
                            checkTask = null;
                            break;
                        }
                        else {
                            KCPTool.Warn(string.Format("Connect Faild {0} Times.Retry...", counter));
                            checkTask = client.ConnectServer(200, 5000);
                        }
                    }
                }
            }
        }
        
        static async void SendPingMsg() {
            while(true) {
                await Task.Delay(5000);
                if(client != null && client.clientSession != null) {
                    client.clientSession.SendMsg(new NetMsg {
                        cmd = CMD.NetPing,
                        netPing = new NetPing {
                            isOver = false
                        }
                    });
                    KCPTool.ColorLog(KCPLogColor.Green, "Client Send Ping Message.");
                }
                else {
                    KCPTool.ColorLog(KCPLogColor.Green, "Ping Task Cancel");
                    break;
                }
            }
        }
    }
    
}